var indexNumber; //播放节目集下标 
var timer
var backgroundAudioManager = wx.getBackgroundAudioManager() //初始音乐播放器
var audioList
var count = 0
var timer2
var recordtime;
var proIds; //记录当前播放详情页栏目id
var currentPosition;
var lastPosition = 0;
var currentPage;
var lasturl = undefined;
var slidevalue = undefined;
//播放音乐
function playaudio(e, that) {
  indexNumber = that.data.indexNumber
  audioList = that.data.classfilyDataList
  if (audioList.length <= indexNumber) {
    backgroundAudioManager.stop()
    that.setData({
      play: true,
      pause: false,
      indexNumberProgram: -1
    })
  } else {
    console.log("播放playauido方法==" + indexNumber + "=====")
    if (indexNumber == -1) {
      indexNumber = 0;
      that.setData({
        indexNumber: 0,
      })
    }
    //拦截收听状态
    if (interceptAction(that, indexNumber)) {
      if (that.data.info != undefined) {} else {
        todetails(1, that)
      }
      return;
    }

    if (lasturl == undefined) {} else {
      if (lasturl == audioList[indexNumber].playUrl) {} else {
        //调整了节目，清空本地播放进度记录 
        var currentPosition = backgroundAudioManager.currentTime //当前播放时间 
        wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), currentPosition)
      }
    }
    backgroundAudioManager.singer = audioList[indexNumber].season + "." + audioList[indexNumber].title
    backgroundAudioManager.title = audioList[indexNumber].title
    backgroundAudioManager.epname = audioList[indexNumber].title
    backgroundAudioManager.coverImgUrl = audioList[indexNumber].imageUrl
    backgroundAudioManager.src = audioList[indexNumber].playUrl // 设置了 src 之后会自动播放 
    //判断是否切换了音频播放链接



    /*
      记录播放时长,提交给后台,
    */
    //背景音频播放事件
    backgroundAudioManager.onPlay(function() {
      if (that.data.info != undefined) {
        wx.setStorageSync("programid", that.data.info.id);
      } else {
        wx.setStorageSync("programid", that.data.classfilyDataListProgram[that.data.indexNumberProgram].id);
      }
      console.log("onPlay....")
      wx.setStorageSync("playstatus", 1) //播放状态
      that.setData({
        pause: true
      })

      //判断是否切换了音频播放链接
      if (lasturl == undefined) {
        recordtime = new Date().getTime();
      } else {
        if (lasturl == backgroundAudioManager.src) {
          recordtime = new Date().getTime();
        } else {
          //调整了节目，清空本地播放进度记录 
          // wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), 0)
          recordlistentime(that)
        }
      }

      //记录当前播放的url 
      lasturl = backgroundAudioManager.src;
      record(that) //调用方法保存历史记录
      listenRecordHistory(that)
    })
    backgroundAudioManager.onSeeking(function() {
      console.log("正在缓冲中..")
      wx.showLoading({
        title: "正在缓冲中..."
      })
    })

    backgroundAudioManager.onSeeked(function() {

      var duration = backgroundAudioManager.duration; //总时长
      currentPosition = backgroundAudioManager.currentTime //当前播放时间 
      currentPage.setData({
        currentPosition: stotime(currentPosition),
        duration: stotime(duration),
        sliderValue: Math.floor(currentPosition * 100 / duration),
      })
      console.log("缓冲完毕")
      wx.hideLoading()
    })
    //背景音频自然播放结束事件
    backgroundAudioManager.onEnded(function() {
      console.log("onEnded....")
      wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), 0)
      currentPosition = 0;
      that.setData({
        currentPosition: 0,
        duration: 0,
        sliderValue: 0, //获取播放进度
        pause: false
      })
      var e = null
      recordlistentime(that)
      next(e, that)
    })
    //背景音频播放进度更新事件
    backgroundAudioManager.onTimeUpdate(function() {

      var status = wx.getStorageSync("playstatus");
      var duration = backgroundAudioManager.duration; //总时长
      currentPosition = backgroundAudioManager.currentTime //当前播放时间 
      var programid = wx.getStorageSync("programid")
      if (proIds == programid) {
        console.log("slidevalue" + slidevalue)
        console.log("currentPosition" + currentPosition)
        currentPage.setData({
          currentPosition: stotime(currentPosition),
          duration: stotime(duration),
          sliderValue: Math.floor(currentPosition * 100 / duration),
        })
        const cp = wx.getStorageSync("currentPosition" + wx.getStorageSync("programid"));

        // 判断 暂停时保存的播放时间  是否快进
        if (cp != undefined) {
          if (Math.abs(parseInt(cp) - lastPosition) > 4) {
            currentPage.setData({
              currentPosition: stotime(cp),
              duration: stotime(duration),
              sliderValue: Math.floor(cp * 100 / duration),
            })

            backgroundAudioManager.seek(parseInt(cp))
            lastPosition = cp
          }
        }
      }
    })
    //背景音频停止事件 ，调用后台接口记录总时长
    backgroundAudioManager.onStop(function() {
      console.log("onStop....")
      that.setData({
        pause: false
      })
      wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), currentPosition)
      recordlistentime(that)
      var srcurl = backgroundAudioManager.src;
      console.log(srcurl);
      if (srcurl != undefined) {
        if (srcurl.indexOf("http://ttbt.client.cdn.soundatm.com") != -1) {
          return
        }
      }
      wx.setStorageSync("playstatus", 0) //播放状态
    })
    //背景音频暂停事件
    backgroundAudioManager.onPause(function() {
      that.setData({
        pause: false
      })
      console.log("onPause....")
      wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), currentPosition)
      recordlistentime(that)


      var srcurl = backgroundAudioManager.src;
      console.log(srcurl);
      if (srcurl != undefined) {
        if (srcurl.indexOf("http://ttbt.client.cdn.soundatm.com") != -1) {
          return
        }
      }
      wx.setStorageSync("playstatus", 0) //播放状态
    })
    //音频加载中事件，当音频因为数据不足，需要停下来加载时会触发
    backgroundAudioManager.onWaiting(function() {
      wx.showLoading({
        title: "正在缓冲中..."
      })
      setTimeout(function() {
        wx.hideLoading()
      }, 1000)
    })
    //背景音频播放错误事件
    backgroundAudioManager.onError(function(e) {
      var message = ""
      if (e.errCode == "10001") {
        message = "音频系统错误";
      } else if (e.errCode == "10003") {
        message = "音频文件错误";
      } else if (e.errCode == "10004") {
        message = "音频格式错误";
      } else if (e.errCode == "-1") {
        message = "音频未知错误";
      }
      wx.showLoading({
        title: message
      })
      setTimeout(function() {
        wx.hideLoading()
      }, 4000)
    })
  }
}

function recordlistentime(that) {
  var seasonId = audioList[indexNumber].id;
  var data
  console.log((new Date().getTime() - recordtime))
  var recordduration = (new Date().getTime() - recordtime) / 1000;
  console.log("recordduration" + recordduration)
  if (recordduration < 1) {
    return
  }
  if (that.data.info != undefined) {
    data = {
      timeLength: recordduration,
      userId: wx.getStorageSync("userId"),
      seasonId: seasonId,
      programId: that.data.info.id
    }
  } else {
    data = {
      timeLength: recordduration,
      userId: wx.getStorageSync("userId"),
      seasonId: seasonId,
      programId: that.data.classifyProgramId
    }
  }
  getApp().request(getApp().globalData.https + "/hd/listen/honbao",
    "post", data,
    function(res) {
      console.log("记录成功" + JSON.stringify(res))
      recordtime = new Date().getTime();
    })
}
//播放进度、时间刷新方法
function setDuration(that) {}
/**
 * 跳转到播放详情页面
 */
function todetails(ind, that) {
  let audioList = that.data.classfilyDataListProgram
  var indexNumbers = that.data.indexNumberProgram; //当前操作对象的 index
  var season = audioList[indexNumbers].currentSeason;
  var id = audioList[indexNumbers].id;

  //wx.setStorageSync("programid", id);

  that.setData({
    playBthidShow: "play"
  })
  if (that.data.history == undefined) {
    wx.navigateTo({
      url: "../../day_day_listen/details/details?id=" + id + "&season=" + season + "&pop=",
      success: function() {},
      fail: function() {}
    })
  } else {
    wx.navigateTo({
      url: "../day_day_listen/details/details?id=" + id + "&season=" + season + "&pop=" + true,
      success: function() {},
      fail: function() {}
    })
  }

}

//暂停播放
function stopaudio(e, that) {
  clearInterval(timer)
  clearInterval(timer2)
  //   const sliderValue = that.data.sliderValue 
  //   wx.setStorageSync("sliderValue", sliderValue)
  backgroundAudioManager.pause();
  wx.setStorageSync("playstatus", 0) //播放状态
  console.log("暂停")
}



//手动调整播放进度条。。。
function bindSliderchange(e, that) {
  let value = e.detail.value
  slidevalue = value;
  console.log("========" + e.detail.value)
  var duration = backgroundAudioManager.duration
  backgroundAudioManager.seek(value * duration / 100)
}

//下一集
function next(e, that) {
  if (that.data.indexNumber >= that.data.classfilyDataList.length) {
    that.setData({
      //   sliderValue: 0,
      status: 0,
      indexNumberProgram: -1
    })
    wx.setStorageSync("playstatus", 0) //播放状态
    return
  }
  //需要判断下一集是否可以听
  that.setData({
    indexNumber: that.data.indexNumber + 1
  })

  wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), 0)
  var e = null
  playaudio(e, that)
}



//拦截判断处理
function interceptAction(that, itemindex) {
  var itemlist = that.data.classfilyDataList
  //判断是否可试听 

  if (that.data.info != undefined) {
    if (that.data.info.category == 0) {
      //免费
    } else {
      //收费节目，未付费做拦截处理
      if (that.data.info.everySeasonBuy != 1) {
        //整集购买
        if (!that.data.info.listen) {
          if (that.data.info.shareStatus == 1) {
            //不可分享，必须付费
            if (itemlist[itemindex].tryStatus == 0) {
              //可试听,不做拦截
            } else {
              //不可试听,需要弹购买窗，拦截处理
              if (that.data.info != undefined) {
                if (that.data.info.everySeasonBuy != 1) {
                  //整集购买弹窗
                  if (!that.data.jumpalready) {
                    that.pay()
                  }
                } else {
                  //分集购买弹窗
                  that.buypopclick(itemindex)
                }
              }
              return true
            }
          } else {
            //可分享免费听的
            if (itemlist[itemindex].tryStatus == 0) {
              //可试听,不做拦截
            } else {
              //不可试听,需要弹分享窗,拦截处理
              if (that.data.info != undefined) {
                that.setData({
                  collectshow: true
                })
              }

              return true
            }
          }
        }
      } else {
        if (that.data.info.shareStatus == 1) {
          //不可分享，必须付费
          if (itemlist[itemindex].tryStatus == 0) {
            //可试听,不做拦截
          } else {
            if (itemlist[itemindex].buySelf != 1) {
              //分集购买弹窗
              if (that.data.info != undefined) {
                that.buypopclick(itemindex)
              }
              return true
            }

          }
        } else {
          //可分享免费听的
          if (itemlist[itemindex].tryStatus == 0) {
            //可试听,不做拦截
          } else {
            //不可试听,需要弹分享窗,拦截处理
            if (that.data.info != undefined) {
              that.setData({
                collectshow: true
              })
            }
            return true
          }
        }
      }
    }
  } else {
    if (that.data.classfilyDataListProgram[that.data.indexNumberProgram].category == 0) {
      //免费
    } else {
      //收费节目，未付费做拦截处理
      if (that.data.classfilyDataListProgram[that.data.indexNumberProgram].everySeasonBuy != 1) {
        //整集购买
        if (!that.data.classfilyDataListProgram[that.data.indexNumberProgram].listen) {
          if (that.data.classfilyDataListProgram[that.data.indexNumberProgram].shareStatus == 1) {
            //不可分享，必须付费
            if (itemlist[itemindex].tryStatus == 0) {
              //可试听,不做拦截
            } else {
              //不可试听,需要弹购买窗，拦截处理
              // if (that.data.classfilyDataListProgram[that.data.indexNumberProgram].everySeasonBuy != 1) {
              //   //整集购买弹窗
              //   that.pay()
              // } else {
              //   //分集购买弹窗
              //   that.buypopclick(itemindex)
              // }
              return true
            }
          } else {
            //可分享免费听的
            if (itemlist[itemindex].tryStatus == 0) {
              //可试听,不做拦截
            } else {
              //不可试听,需要弹分享窗,拦截处理
              // that.setData({
              //   collectshow: true
              // })
              return true
            }
          }
        }
      } else {
        if (that.data.classfilyDataListProgram[that.data.indexNumberProgram].shareStatus == 1) {
          //不可分享，必须付费
          if (itemlist[itemindex].tryStatus == 0) {
            //可试听,不做拦截
          } else {
            if (itemlist[itemindex].buySelf != 1) {
              //分集购买弹窗
              // that.buypopclick(itemindex)
              return true
            }

          }
        } else {
          //可分享免费听的
          if (itemlist[itemindex].tryStatus == 0) {
            //可试听,不做拦截
          } else {
            //不可试听,需要弹分享窗,拦截处理
            // that.setData({
            //   collectshow: true
            // })
            return true
          }
        }
      }
    }
  }

}

//上一集
function last(e, that) {
  if (that.data.indexNumber <= 0) {
    console.log("ddddd等于零了------------")
    wx.setStorageSync("playstatus", 0) //播放状态
    return
  }
  console.log("不等于零了--------==----")
  that.setData({
    indexNumber: that.data.indexNumber - 1
  })

  wx.setStorageSync("currentPosition" + wx.getStorageSync("programid"), 0)
  var e = null
  playaudio(e, that)
}



//时间计时器。。。
function stotime(s) {
  let t = '';
  if (s > -1) {
    // let hour = Math.floor(s / 3600);
    let min = Math.floor(s / 60) % 60;
    let sec = parseInt(s % 60);
    // if (hour < 10) {
    //   t = '0' + hour + ":";
    // } else {
    //   t = hour + ":";
    // }

    if (min < 10) {
      t += "0";
    }
    t += min + ":";
    if (sec < 10) {
      t += "0";
    }
    t += sec;
  }

  return t;
}

module.exports = {
  indexNumber: indexNumber, //当前播放下标
  setDuration: setDuration, //进度相关展示数据
  bindSliderchange: bindSliderchange, //进度条拖动
  // playcontinue: playcontinue, //
  playaudio: playaudio, //播放
  stopaudio: stopaudio, //停止
  next: next, //下一个
  cleartimer2: cleartimer2,
  last: last, //上一个
  audio: backgroundAudioManager,
  getProgramCurrentSeason: getProgramCurrentSeason, //获取栏目下的集列表
  listenRecordHistory: listenRecordHistory, //用户收听记录数
  record: record, //历史收听记录
}


/**
 * 获取单个栏目下所有集数列表
 */
function getProgramCurrentSeasonListCk(id, data, that) {
  if (that.data.totalPages <= that.data.page) {
    return true;
  } else {
    if (that.data.classfilyDataList.length <= that.data.indexNumber) {
      that.setData({
        page: that.data.page + 1
      })
      var data = {
        startPoint: that.data.page,
        maxPage: 10,
        userId: wx.getStorageSync("userId")
      }
      getProgramCurrentSeason(id, data, that);
      return false;
    } else {
      return true;
    }
  }
  return true;
}


/**
 * 获取单个栏目下所有集数列表
 */
function getProgramCurrentSeason(id, data, that) {
  proIds = id;
  currentPage = that;
  var rate = that.data.indexNumber / 10
  rate = Math.floor(rate)
  console.log("startPoint" + that.data.page)
  var data
  if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
    data = {
      startPoint: that.data.page,
      maxPage: that.data.page == 1 ? (10 * rate + 10) : 10
    }
  } else {
    data = {
      "userId": wx.getStorageSync("userId"),
      startPoint: that.data.page,
      maxPage: that.data.page == 1 ? (10 * rate + 10) : 10
    }
  }

  getApp().requestLoading(getApp().globalData.https + "programResource/seasons/" + id,
    "get", data, "加载中..",
    function(res) {
      console.log(JSON.stringify(res))
      if (res.code == 0) {
        if (id != wx.getStorageSync("programid")) {
          that.setData({
            classfilyDataList: []
          })
        }
        console.log(res.data.data)
        that.setData({
          classfilyDataList: that.data.classfilyDataList.concat(res.data.data),
          totalPages: res.data.totalPages,
          indexNumber: that.data.indexNumber,
          programidSelect: id,
        })
        // listenRecordHistory(that)
        lastPosition = 0;
        if (!that.data.ispop) {
          var programid = wx.getStorageSync("programid")
          if (id == programid) {
            console.log("同一个栏目" + wx.getStorageSync("playstatus"))
            if (wx.getStorageSync("playstatus") == 1) {
              //正在播放
            } else {
              if (backgroundAudioManager.src != undefined) {
                backgroundAudioManager.play();
              } else {
                playaudio(null, that)
              }
            }
          } else {
            if (that.data.info == undefined) {
              playaudio(null, that)
            }
          }
        }

      }
    }
  );
}

function cleartimer2() {
  clearInterval(timer2)
}


/**
 * 用户收听节目记录数
 */
function listenRecordHistory(that) {
  var dataparm = {
    "seasonId": that.data.classfilyDataList[that.data.indexNumber].id,
    "userId": wx.getStorageSync("userId")
  }
  getApp().request(getApp().globalData.https + "programResource/popularRecord",
    "post", dataparm,
    function(res) {
      console.log("收听节目添加记录：" + JSON.stringify(res))
    }
  )
}

/**
 * 历史收听记录
 * 记录收藏，历史，已购栏目(**“已购”不可调这个借口，该接口只记录历史、收藏)
 */
function record(that) {
  if (wx.getStorageSync("userId") == '' || wx.getStorageSync("userId") == undefined) {
    return
  }

  var dataparm = {
    "programId": that.data.programid,
    //seasonId值需要优化，当列表list.size()小于indexNumber需要继续加载数据，否则会报错找不到id  TODO...
    "seasonId": that.data.classfilyDataList[that.data.indexNumber].id,
    "status": 0,
    "userId": wx.getStorageSync("userId")
  }
  getApp().request(getApp().globalData.https + "programResource/mark",
    "post", dataparm,
    function(res) {
      console.log("历史记录添加调用结果：" + JSON.stringify(res))
    }
  )
}